package com.traitswu.simple.demo.store;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;


public class LocalStore implements Store {

    @Override
    public FileDesc save(InputStream inputStream, String dir, String fileName) throws IOException {
        Path dirPath = Paths.get(dir);
        if (Files.notExists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        File file = new File(dir, renameWithVersion(fileName));
        if (file.exists()) {
            throw new IllegalStateException("File(" + fileName + ") existed.");
        }

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        while (true) {
            int n = inputStream.read(buffer);
            if (n == -1) {
                break;
            }

            fileOutputStream.write(buffer, 0, n);
        }
        fileOutputStream.close();
        return new FileDesc(fileName, file.getAbsolutePath());
    }

    /**
     * @param fileDesc url is absolute path
     * @return
     * @throws IOException
     */
    @Override
    public InputStream read(FileDesc fileDesc) throws IOException {
        return Files.newInputStream(Paths.get(fileDesc.getUrl()));
    }

    @Override
    public boolean move(String target, String dest) throws IOException {
        Path targetPath = Paths.get(target);
        Path destPath = Paths.get(dest);
        if (Files.exists(destPath)) {
            throw new IllegalStateException("File existed:" + dest);
        }

        if (Files.notExists(destPath.getParent())) {
            Files.createDirectories(destPath.getParent());
        }

        Path path = Files.move(targetPath, destPath, StandardCopyOption.ATOMIC_MOVE);
        return Files.exists(path);
    }

    private String renameWithVersion(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index == -1) {
            return fileName + "." + System.currentTimeMillis();
        }
        String ext = fileName.substring(index);
        String prefix = fileName.substring(0, index);
        return prefix + "." + System.currentTimeMillis() + ext;
    }


}
